(function(){
	$(function(){

	//定义
		var telInput = $('#purchase-phone-number');
		var codeInput = $('#purchase-check-code');
		var errorInfo = $('.code-error-info');
		var pointInput = $('#use-limit')
		var couponSelect = $('#pay-voucher-choose')
		var leftPoint = $('.left-point')
		var avilablePoint = $('.avilable-point')
		var pointToMoney = $('.point-to-money');

	//绑定
		$('.purchase-agent-title input').click(function(){
			var classname = $(this).attr('class');
			var agent = $('.purchase-agent-phone')
			//先清空
			pointInput.val('');
			leftPoint.removeAttr('data-point').html('???')
			couponSelect.empty().append($("<option value=''>请选择</option>"))

			if(classname=='purchase-myself'){
				agent.hide()
				api.solo('getCouponPoint',[],function(d){
					if(d.resultCode == 200){
						couponPoint(d.data.coupon,d.data.point)	
						calMoney();
					}else{
						alert('个人积分优惠券获取失败')
					}
					
				})
				telInput.attr('disabled', true);
			}else{
				agent.show()
				telInput.removeAttr('disabled')
			}
		})
		$('.agent-get-code').click(function(e){
			e.preventDefault();
			var tel = telInput.val()
			if(tel.split("").length != 11){alert("请输入正确的手机号"); return false;}
			if(tel==_userBaseInfo.username){alert('不能输入自己的手机号'); return false;}
			api.solo('getCode',[tel,'agent'],function(d){
				if(d.state == 200){
					alert('验证码已发送')
				}else{
					alert('发送失败，请重试')
				}
			})
			$(".agent-confirm-code").click(function(e){
				e.preventDefault()
				var code = codeInput.val()
				api.solo('checkCodeAndGetInfo',[tel,code],function(d){
					if(d.resultCode==200){
						alert("验证成功，现在您可以选择您的优惠券和积分");
						errorInfo.html("验证成功")
						couponPoint(d.data.coupon,d.data.point)
					}else{
						alert('验证码错误');
						errorInfo.html(d.title)
					}
				})
			})
		})
		pointInput.bind('input propertyChange', function(event) {
			//alert(1)
			calMoney()
		});
		couponSelect.change(function(){
			calMoney()
		})
		$('#confirm-button').click(function(e){
			e.preventDefault();
			//表单完整性检测

			//是否冻结
			if( $("#rest-pay").is(':checked') && _userInfo.money_usable != 1 ){
				alert("抱歉，您的余额支付已被冻结，您可以使用支付宝付款或联系客服");
				return false;
			}

			//地址
			var addressVal = $("input[name='user_address_id']").val()
			if(addressVal == null || addressVal == 0 ){
				alert('请填写您的地址');
				return false;
			}
			if( $("#rest-pay").is(':checked') && $(".purchase-myself").is(':checked') ){
				openAlertBg();	
			}else{
				$("#container > div.main-container > form").submit();
			}
			
			//$("form").trigger('submit')
		})
		$(".alert-bg .close").click(function(e){
		    e.preventDefault();
		    $(this).closest(".alert-bg").hide();
		    //clearInterval(ieCheck);
		});
		(function(){
			var codeInput = $('#test-code')
		    var getCodeButton = $('.getCodeButton')
		    var $submitButton=$('.info-affirm');
		    var submitAble=false;
		    var currentAmount=0;
		    //发送验证码
		    getCodeButton.click(function(e){
		        e.preventDefault();
		        //冻结
		        if( _userInfo.money_usable != 1 ){
		            alert("抱歉，您的余额支付已被冻结，您可以使用支付宝付款或联系客服");
		            $("#alipay").prop('checked', true)
		            return false;
		        }

		        var tel=_userBaseInfo.username;
		        var type='pay';
		        console.log(tel,type,currentAmount)
		        api.solo('getAmountCode',[tel,type,calMoney()],function(d){
		            alert(d.state==200?'验证码已发送请查收':d.title)

		            //////////////

		            //兼容弱智浏览器
		            //alert(IS_IE9)
		            var IS_IE9 = IS_IE9 || false;
		            if(IS_IE9){
		                //alert(1)
		                var ieCheck = setInterval(function(){
		                    //alert(1)
		                    checkCode()
		                },1500);
		            }else{
		                //alert(2)
		            }
		        })
		    })

		    //验证验证码
		    
		    codeInput.bind("input propertyChange", function(){
		        checkCode()
		    })
		    function checkCode(){
		        //$("#pay-way-money").prop("checked",true);
		        var tel=_userBaseInfo.username;
		        var code = codeInput.val();
		        //alert(1)
		        if(code.length!=6){
		            $('.code-right').hide();
		            $('.code-wrong').show();
		            return false;
		        }

		        api.solo('checkCode',[tel,code],function(d){
		            submitAble=false;
		            //alert(submitAble)
		            if(d.state==200){
		                submitAble=true;
		                $('.code-right').show();
		                $('.code-wrong').hide();
		            }else if(d.state==400) {
		                $('.code-right').hide();
		                $('.code-wrong').show();
		                alert(d.title);
		            }else{
		                $('.code-right').hide();
		                $('.code-wrong').show();
		            }
		        })
		    }
		    

		    $submitButton.click(function(){
		        //冻结
		        if( $("#pay-way-money").is(':checked') && _userInfo.money_usable != 1 ){
		            alert("抱歉，您的余额支付已被冻结，您可以使用支付宝付款或联系客服");
		            $("#alipay").prop('checked', true)
		            return false;
		        }


		        if(submitAble|| $("#alipay").prop("checked")){
		            //document.getElementById('order-pay').submit();
		            $("#container > div.main-container > form").submit();
		        }else{
		            alert("验证码错误,请再次确认");
		        }
		    })
		})()
			


	//逻辑
		//获取用户信息
		$.ajax({
		    url: '../api/user/getUserInfo',
		    type: 'GET',
		    //aysnc:false,
		    dataType: 'json',
		    success:function(d){
		        if(d.state==200){
		            window._userId = d.user.id;
		            window._userBaseInfo = d.user;
		            window._userInfo = d.userInfo;
		        }
		        calMoney();
		    },
		    error:function(){
		        alert('获取用户信息失败，请尝试刷新');
		    }
		})
		$('.purchase-myself').click()
		calMoney()


	//函数
		function couponPoint(coupon,point){
			//积分

			//剩余积分
			point = parseInt(point,10);
			leftPoint.html(point).attr('data-point', point);
			//剩余可用积分
			var leftAvaliblePoint = Math.floor(point/10)*10;

			//可用积分
            var tmp10Total=  Math.floor(parseInt(_orderTotal*5)/10)*10;
			avilablePoint.html(tmp10Total)

			//最低积可用
			var lowestPoint = tmp10Total<point?tmp10Total:leftAvaliblePoint;
			pointInput.val(lowestPoint)

			calMoney()

			pointInput.bind('input propertyChange', function(event) {
				console.log($(this).val(),tmp10Total)
				if( isNaN($(this).val()) ){
					alert('请输入整数数字');
					$(this).val(lowestPoint)
				}
				if($(this).val() < 0){
					alert('积分小于 0')
					$(this).val(0)
				}else if($(this).val() > leftAvaliblePoint){
					alert('超过积分限额，只能使用整十的积分');
					$(this).val(lowestPoint)
				}else if($(this).val() > point){
					alert('超过积分限额');
					$(this).val(lowestPoint)
				}else if($(this).val() > tmp10Total){
					alert('超过单次积分使用限额')
					$(this).val(lowestPoint)
				}
				calMoney()
			});
			pointInput.blur(function(event) {
				if(parseInt($(this).val(),10)%10 != 0){
					alert('请输入整十数字')
					$(this).val( Math.floor(parseInt($(this).val(),10)/10)*10 )
				}
			});
			//优惠券
			//var couponBox = $('#pay-voucher-choose');
			var optionTpl = $("<option></option>")
			if(coupon.length>0){
				for(var i=0,length=coupon.length;i<length;i++){
					console.log(_shopList)
					console.log(coupon[i]['company'])
					for(var j in _shopList){
						if(_shopList[j]==coupon[i]['company'] || coupon[i]['company']==null){
							var newOption = optionTpl.clone();
							newOption.html("商家："+coupon[i].company+" 金额："+ coupon[i].value)
							.val(coupon[i].id)
							.attr('data-money', coupon[i].value);
							couponSelect.append(newOption)
							break;
						}

					}
				}
			}
		}

		//test
		//var _shopList = ['酷袋子','萌系工厂']
		//api.solo('checkCodeAndGetInfo',[15150024719,1],function(d){
		//		couponPoint(d.data.coupon,d.data.point)
		//})

		function calMoney(){
			var moneyStack = {};
			moneyStack['orderMoney'] = _orderTotal;
			moneyStack['point'] = -(parseInt($('#use-limit').val())/1000).toFixed(2);
			moneyStack['coupon'] = -($('#pay-voucher-choose').find('option:selected').attr('data-money'));
			var finalTotal = 0
			for(var i in moneyStack){
				if(typeof moneyStack[i] == 'undefined' || moneyStack[i] == null || isNaN(moneyStack[i])){
					moneyStack[i] = 0;
				}
				finalTotal += moneyStack[i];
			}
			console.log(moneyStack)
			//改变积分抵用
			pointToMoney.html(-moneyStack['point'])
			//改变第一个订单价格
			var firstOrderAmount = $("input[name='shop[0][order_amount]']")
			var firstPayAmount = $("input[name='shop[0][payment_amount]']")
			firstOrderMoney = firstOrderAmount.val();
			firstPayAmount.val( (parseFloat(firstOrderMoney) + parseFloat(moneyStack['point']) + parseFloat(moneyStack['coupon'])).toFixed(2) )
			//改变价格
			$('#order-final-total').html(finalTotal)
			$('#order-final-input').val(finalTotal)
			//改变支付方式的价格
			var userMoney    = parseFloat(_userInfo.money).toFixed(2);
			console.log(userMoney)
			var restPayInput = $('#rest-pay');
			var aliPayInput  = $('#alipay')
			var $userMoney 	 = $('.pay-way .js-pay-usermoney').show()
			var $leftPay   	 = $('.pay-way .js-pay-leftpay').hide()
			var $aliPay    	 = $('.pay-way .js-pay-alipay').hide()
			var $userLeft    = $('.pay-way .js-pay-usermoneyleft').hide()
			var $loading     = $('.pay-way .js-pay-loading').hide();

			if(isNaN(userMoney)){
				$loading.show()
                $userMoney.hide()
				restPayInput.attr({
					'disabled':true,
					'checked':false
				})
			}else{
				$loading.hide()

				$userMoney.find('b').html(userMoney)
				if(userMoney == 0){
					restPayInput.attr({
						'disabled':true,
						'checked':false
					})
					aliPayInput.attr('checked',true)
					aliPayInput.prop('checked',true)

				}else{
					restPayInput.attr({
						'disabled':false,
						'checked':true
					}).prop('checked',true)

					if(userMoney >= finalTotal){
						$leftPay.find('b').html(finalTotal)
						$userLeft.find('b').html(parseFloat(userMoney-finalTotal).toFixed(2));
						$userLeft.show()
					}else{
						$leftPay.find('b').html(userMoney)
						$aliPay.find('b').html(parseFloat(finalTotal-userMoney).toFixed(2))
						$aliPay.show()
					}
					$leftPay.show()
					//if()
				}
			}

			
			return finalTotal;
		}

		window['calMoney'] = calMoney;

		function openAlertBg(){
		    $(".alert-bg.order-pay").show();
		    //$(".alert-bg #order-id").val($current.closest("tr").attr('data-id'));
		    //console.log($current.closest("tr").attr('data-id'));
		    var userMoney=Number(_userInfo.money);
		    currentAmount=Number($("#order-final-total").html());
		    var s="";
		    if(userMoney<currentAmount){
		        s="(账户余额"+userMoney+"元，余额支付"+userMoney+"元，其余"+(currentAmount-userMoney).toFixed(2)+"元使用支付宝)";
		    }else{
		        s="(账户余额"+userMoney+"元，余额支付"+currentAmount.toFixed(2)+"元)";
		    }
		    $(".alert-bg #pay-way-money-label").text(s);
		}

		
		
	});
})();
